#pragma once
#include<string>
#include<string.h>
#include<iostream>
#include<unordered_map>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
class User
{
public:
    User(const std::string &ip, const uint16_t &port)
        : ip_(ip), port_(port)
    {}
    ~User()
    {}
public:
    std::string ip_;//用于的ip
    uint16_t port_;//用户的端口
};

//使用用户的IP+端口号来标识唯一性！
//这个类要有添加用户，删除的用户的功能
class OnlineUser
{
public:
    OnlineUser()
    {}

    ~OnlineUser()
    {}

    void addUser(const std::string &ip, const uint16_t &port)
    {
        std::string id = ip + "-" + std::to_string(port);//构建用户id
        Users_.insert({id,User(ip,port)});
    }

    void DelUser(const std::string &ip, const uint16_t &port)
    {
        std::string id = ip + "-" + std::to_string(port);//构建用户id
        Users_.erase(id);
    }

    bool isOnline(const std::string &ip, const uint16_t &port)
    {
        std::string id = ip + "-" + std::to_string(port);//构建用户id
        return Users_.find(id) != Users_.end();
    }

    void broadcastMessage(int sockfd,const std::string& ip,const uint16_t& port,const std::string& message)
    {
        //将收到的信息转发给所有的在线用户！
        for(auto& user:Users_)
        {

            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer)); // 清0
            peer.sin_family = AF_INET;
            peer.sin_port = htons(user.second.port_);
            peer.sin_addr.s_addr = inet_addr(user.second.ip_.c_str());

            std::string s = ip + "-"+ to_string(port)+"# ";
            s+=message;
            sendto(sockfd, s.c_str(), s.size(), 0, (struct sockaddr *)&peer, sizeof(peer));
        }
    }
private:
    std::unordered_map<std::string,User> Users_;
};